package com.winenine999.realm;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.winenine999.custom.dao.CSyauthorityMapper;
import com.winenine999.custom.dao.CSyuserMapper;
import com.winenine999.model.Syuser;

public class MyRealm extends AuthorizingRealm {
	@Autowired
	private CSyauthorityMapper cSyauthorityMapper;
	@Autowired
	private CSyuserMapper cSyuserMapper;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		String userName=(String) principals.getPrimaryPrincipal();
		System.out.println("userName:"+userName);
		Syuser syuser=cSyuserMapper.findUserByName(userName);
      //  String userName = (String) principals.fromRealm(getName()).iterator().next();  
     //   Syuser syuser =cSyuserMapper.findUserByName(userName);
		
		//simpleAuthorInfo.addRole("zz");
		
        if (syuser != null&&syuser.getId()!=null) {  
        	Set<String> sets=cSyauthorityMapper.findPermissinSignsByUserId(syuser.getId());
        	for(String set:sets){
        		System.out.println("set:"+set);
        	}
        	simpleAuthorInfo.addStringPermissions(sets);
        }		
		return simpleAuthorInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)throws AuthenticationException {
		UsernamePasswordToken token =(UsernamePasswordToken) authcToken;
		String userName=token.getUsername();
		token.getPassword();
		Syuser syuser=cSyuserMapper.findUserByName(userName);
		//袁说视频用法
		//String userName=authcToken.getPrincipal().toString();
		//Syuser syuser=selectSyuserByName();
		//authcInfo = new SimpleAuthenticationInfo(syuser.getName(), syuser.getPassword(), userName);
		AuthenticationInfo authcInfo =null;
		if(syuser!=null){
			authcInfo = new SimpleAuthenticationInfo(syuser.getName(), syuser.getPassword(), userName);
			return authcInfo;
		}
		/* authcInfo = new SimpleAuthenticationInfo("li", "123", userName);*/
	
	return authcInfo;
		
	}

}
